package com.wenbo.ocr.service.impl;

import ai.onnxruntime.OnnxTensor;
import com.alibaba.fastjson.JSONArray;
import com.wenbo.ocr.service.OCREngine;
import com.wenbo.ocr.utils.IOUtils;
import com.wenbo.ocr.utils.ImageUtils;
import com.wenbo.ocr.utils.LogUtils;
import com.wenbo.ocr.utils.ONNXRuntimeUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author wenbo
 * @Date 2023/10/18 22:01
 **/
@Service
public class OCREngineOldImpl implements OCREngine {
    private static JSONArray charsetArray;
    private static File modelFile;

    public OCREngineOldImpl() {
    }

    @Override
    public String recognize(BufferedImage image) {
        try {
            ONNXRuntimeUtils onnx = new ONNXRuntimeUtils();

            String var18;
            label68: {
                Object var3;
                label67: {
                    try {
                        if (image == null) {
                            LogUtils.printMessage("OCR输入图像不能为空", LogUtils.Level.ERROR);
                            var3 = null;
                            break label67;
                        }

                        if (modelFile != null && modelFile.exists() && charsetArray != null) {
                            image = ImageUtils.resize(image, 64 * image.getWidth() / image.getHeight(), 64);
                            image = ImageUtils.toGray(image);
                            long[] shape = new long[]{1L, 1L, (long)image.getHeight(), (long)image.getWidth()};
                            float[] data = new float[(int)(shape[0] * shape[1] * shape[2] * shape[3])];
                            image.getData().getPixels(0, 0, image.getWidth(), image.getHeight(), data);

                            for(int i = 0; i < data.length; ++i) {
                                data[i] /= 255.0F;
                                data[i] = (float)(((double)data[i] - 0.5D) / 0.5D);
                            }

                            OnnxTensor indexTensor = (OnnxTensor)onnx.run(modelFile.getAbsolutePath(), Map.of("input1", onnx.createTensor(data, shape))).get(0);
                            LogUtils.printMessage("score type: " + indexTensor.getInfo().type.name(), LogUtils.Level.DEBUG);
                            LogUtils.printMessage("score shape: " + Arrays.toString(indexTensor.getInfo().getShape()), LogUtils.Level.DEBUG);
                            long[][] index = (long[][])indexTensor.getValue();
                            StringBuilder words = new StringBuilder();
                            long[] var8 = index[0];
                            int var9 = var8.length;

                            for(int var10 = 0; var10 < var9; ++var10) {
                                long i = var8[var10];
                                words.append((String)charsetArray.get((int)i));
                            }

                            var18 = words.toString();
                            break label68;
                        }

                        LogUtils.printMessage("OCR模型配置缺失", LogUtils.Level.ERROR);
                        var3 = null;
                    } catch (Throwable var14) {
                        try {
                            onnx.close();
                        } catch (Throwable var13) {
                            var14.addSuppressed(var13);
                        }

                        throw var14;
                    }

                    onnx.close();
                    return (String)var3;
                }

                onnx.close();
                return (String)var3;
            }

            onnx.close();
            return var18;
        } catch (Exception var15) {
            LogUtils.printMessage("OCR识别异常", var15, LogUtils.Level.ERROR);
            return null;
        }
    }

    static {
        try {
            InputStream is = ClassPathResource.class.getResourceAsStream("/d4/common_old_charset.json");

            try {
                charsetArray = JSONArray.parseArray(new String(is.readAllBytes(), "UTF-8"));
                String javaTmpDir = System.getProperty("java.io.tmpdir", ".");
                File appTmpDir = new File(javaTmpDir, "d4ocr");
                appTmpDir.mkdirs();
                modelFile = new File(appTmpDir, "common_old.onnx");
                IOUtils.extractJarResource("/d4/common_old.onnx", modelFile);
            } catch (Throwable var4) {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Throwable var3) {
                        var4.addSuppressed(var3);
                    }
                }

                throw var4;
            }

            if (is != null) {
                is.close();
            }
        } catch (Exception var5) {
            LogUtils.printMessage("模型配置加载异常", var5, LogUtils.Level.ERROR);
        }

    }

}
